package edu.kaist.cs442.client.android.common.location.track;

import android.app.IntentService;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.util.Log;
import edu.kaist.cs442.client.android.common.RestServices;
import edu.kaist.cs442.client.android.common.pushutil.register.TrackInstallation;


/**
 * Created with IntelliJ IDEA.
 * User: duyleekun
 * Date: 4/18/12
 * Time: 7:48 PM
 * To change this template use File | Settings | File Templates.
 */
public class TrackService extends IntentService {


	public static LocationManager locationManager;
	LocationListener networkLocationListener =  new TrackLocationListener(this);

	public TrackService() {
		super("LocationUpdater");
	}

	@Override
	protected void onHandleIntent(Intent intent) {
		Log.i("location","request location listener");
		locationManager = (LocationManager) this.getSystemService(LOCATION_SERVICE);
		Location lastLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
		if (lastLocation != null)
		{
			Log.i("location",String.format("Lat = %f Long = %f",lastLocation.getLatitude(),lastLocation.getLongitude()));
			RestServices.getTrackerSVC().updateLocation(TrackInstallation.id(this),lastLocation.getLatitude(),lastLocation.getLongitude());
		}
		locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 10000, 0, networkLocationListener);
	}

	@Override
	public void onDestroy() {
		locationManager.removeUpdates(networkLocationListener);
		super.onDestroy();    //To change body of overridden methods use File | Settings | File Templates.
	}
}
